<template>
    <div class="my-upload">
        <el-upload action="" list-type="picture-card" :http-request="upload" :show-file-list="false">
            <i class="el-icon-plus"></i>
        </el-upload>
        <div v-if="imgUrl != ''" class="img">
            <el-image :src="imgUrl" fit="contain" style="width: 100px; height: 100px;"></el-image>
        </div>
    </div>
</template>

<script>
import { reqOssUpload } from '@/api/oss';
import SparkMD5 from "spark-md5";

export default {
    name: 'my-upload',
    data() {
        return {
            imgUrl: ""
        }
    },
    methods: {
        upload(param) {
            this.calculateMD5(param);
        },
        calculateMD5(param) {
            let file = param.file;
            const chunkSize = 1024 * 1024; // 1MB 分块
            const spark = new SparkMD5.ArrayBuffer(); // 使用spark-md5的ArrayBuffer方法
            const fileReader = new FileReader();
            let offset = 0;

            fileReader.onload = (e) => {
                // 每次读取一块文件数据后，更新MD5计算
                spark.append(e.target.result); // 追加数据到MD5计算器
                offset += chunkSize;

                if (offset < file.size) {
                    // 如果文件还没有读取完，继续读取下一块
                    this.readNextChunk(file, fileReader, offset, chunkSize);
                } else {
                    // 文件读取完，输出最终的MD5值
                    this.md5 = spark.end(); // 获取最终的MD5值
                    const formData = new FormData()
                    formData.append('file', param.file)
                    formData.append('fileMd5', this.md5)
                    formData.append('fileType', param.file.type)
                    this.uploadToOss(formData)
                }
            };

            fileReader.onerror = (error) => {
                console.error('文件读取错误:', error);
            };

            // 开始读取文件的第一块数据
            this.readNextChunk(file, fileReader, offset, chunkSize);
        },
        readNextChunk(file, fileReader, offset, chunkSize) {
            // 读取文件的一个块
            const slice = file.slice(offset, offset + chunkSize); // 获取文件的一个分块
            fileReader.readAsArrayBuffer(slice); // 读取当前分块
        },
        uploadToOss(formData) {
            reqOssUpload(formData).then((res) => {
                this.imgUrl = res.data.downloadUrl;
                this.$emit('callParent', res.data.downloadUrl);
                this.$message.success("上传成功");
            }).catch((error) => {
                this.$message.error(error.msg);
            })
        },
        setImgUrl(url){
            this.imgUrl = url;
        }
    },
}
</script>

<style scoped>
.my-upload{
    display: flex;
    align-items: center;
}

::v-deep .el-upload--picture-card {
    width: 100px !important;
    height: 100px !important;
    line-height: 100px !important;
}

.img{
    margin-left: 20px;
}

</style>